using System;
using System.IO;
using UnityEngine;

public static class FileHandler
{
    //保存数据(json文本，路径，名称），限定只能是继承GameData的
    public static void Save(string filePath,string fileName,GameData data)
    {
        //拼接路径
        string fullPath = Path.Combine(filePath, fileName);
        //捕获错误
        try
        {
            //创建文件夹
            Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
            //转换为str字符串
            string str = JsonUtility.ToJson(data);
            //写入（steam流）
            using(FileStream stream=new FileStream(fullPath,FileMode.Create))
            {
                using(StreamWriter writer=new StreamWriter(stream))
                {
                    writer.Write(str);
                }
            }
        }
        catch (Exception e)
        {
            UnityEngine.Debug.Log("保存错误：<<"+e.ToString());
        }
    }
    //读取数据
    public static T Load<T>(string filePath,string fileName) where T :GameData
    {
        //拼接路径
        string fullPath = Path.Combine(filePath, fileName);

        //读取的str
        string str = "";
        //捕捉
        try
        {
            //文件存在吗
            if(File.Exists(fullPath))
            {
                //读取流
                using(FileStream stream=new FileStream(fullPath,FileMode.Open))
                {
                    using(StreamReader reader=new StreamReader(stream))
                    {
                        str=reader.ReadToEnd();
                        return JsonUtility.FromJson<T>(str);
                    }
                }
            }
        }
        catch(Exception e)
        {
            UnityEngine.Debug.Log("读取错误：<<"+e.ToString());
        }

        return null;
    }
    //删除游戏文件夹
    public static void DeleteFile(string fullPath)
    {
        if(File.Exists(fullPath))
        {
            File.Delete(fullPath);
        }
    }
}